package cn.com.open.itembank.filter;

import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lucky on 2017/7/19.
 */
@Order(1)
@WebFilter(filterName = "AuthorizeFilter", urlPatterns = "/*")
public class UserAuthorizeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        return;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String url = httpRequest.getRequestURI();

        // 例外不验证appkey的情况
        List<String> excluded = new ArrayList<>();
        excluded.add("/itembank/download");
        excluded.add("/health");
        excluded.add("/version");
        excluded.add("/env");
        excluded.add("/dnotdelet/mom.html");
        for (String item : excluded) {
            if (url.indexOf(item) > -1){
                filterChain.doFilter(request, response);
                return;
            }
        }

        String appkey = httpRequest.getHeader("appkey");
        String appsecret = httpRequest.getHeader("appsecret");

        if (StringUtils.isEmpty(appkey) || StringUtils.isEmpty(appsecret)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json; charset=utf-8");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            response.getWriter().write("请求 Header 缺少 appkey、appsecret 参数！");
            return;
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        return;
    }
}
